<?php

class UserController extends Controller
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('view','create','update','delete','index'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        if (Yii::app()->user->checkAccess('readUser')) {
            $this->renderPartial('view', array(
                'model' => $this->loadModel($id),
            ));
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        if (Yii::app()->user->checkAccess('createUser')) {
            $model = new User;
            $this->performAjaxValidation($model,'user_form');
            if (isset($_POST['User'])) {
                $model->attributes = $_POST['User'];
                if ($model->save())
                    $this->redirect(array('index'));
            }
            $this->render('create', array(
                'model' => $model,
            ));
        } else {
            echo 'Error:403';
        }

    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        if (Yii::app()->user->checkAccess('updateUser')) {
            $model = $this->loadModel($id);
             $this->performAjaxValidation($model,'user_form');
            if (isset($_POST['User'])) {
                $model->attributes = $_POST['User'];
                if ($model->save())
                    $this->redirect(array('index', 'id' => $model->user_id));
            }
            $this->render('update', array(
                'model' => $model,
            ));
        } else {
            echo 'Error:403';
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->user->checkAccess('deleteUser')) {
            $this->loadModel($id)->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }else{
            echo 'Error:403';
        }
    }

    /**
     * Manages all models.
     */
    public function actionIndex()
    {
        $model = new User('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['User'])) {
            $model->attributes = $_GET['User'];
        }
        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return User the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

//    public function actionAssign()
//    {
//        $auth=Yii::app()->authManager;
//
//        $auth->createOperation('createUser','create user');
//        $auth->createOperation('readUser','read user information');
//        $auth->createOperation('updateUser','update user information');
//        $auth->createOperation('deleteUser','delete user');
//
//        $role=$auth->createRole('user');
//        $role->addChild('readUser');
//
//        $role=$auth->createRole('admin');
//        $role->addChild('user');
//        $role->addChild('createUser');
//        $role->addChild('updateUser');
//        $role->addChild('deleteUser');
//
//        $auth->assign('admin', 'admin');
//        $auth->assign('user', 'user');
//        $auth->assign('user', 'guest');
//    }

    protected function performAjaxValidation($model, $form_id)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === $form_id) {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
